package com.wujilin.okra.fragment;

import static android.content.DialogInterface.BUTTON_POSITIVE;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_ID;
import static com.wujilin.okra.Okra.T_KEY_RESULT;
import static com.wujilin.okra.Okra.T_OBJECTIVE;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.wujilin.okra.R;
import com.wujilin.okra.database.Sql;

/**
 * 
 * @author Belin Wu
 */
public class OkraDeleteFragment extends DialogFragment implements OnClickListener {
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_confirm_delete, null);
		TextView confirmText = (TextView) view.findViewById(R.id.confirm_delete);
		confirmText.setText(R.string.confirm_delete_okra);
		
		Dialog dialog = new AlertDialog.Builder(getActivity())
				.setTitle(R.string.delete)
				.setView(view)
				.setPositiveButton(android.R.string.ok, this)
				.setNegativeButton(android.R.string.cancel, this)
			.create();
		return dialog;
	}
	
	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (which == BUTTON_POSITIVE) {
			final long objectiveId = getArguments().getLong(EXTRA_OBJECTIVE_ID);
			boolean success = Sql.run(new Runnable() {
				@Override
				public void run() {
					Sql.delete(T_OBJECTIVE, objectiveId);
					Sql.delete(T_KEY_RESULT, "objective_id=?", objectiveId + "");
				}
			});
			if (success) {
				getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
			}
		}
	}

	public static OkraDeleteFragment newInstance(long id) {
		Bundle args = new Bundle();
		args.putLong(EXTRA_OBJECTIVE_ID, id);
		
		OkraDeleteFragment fragment = new OkraDeleteFragment();
		fragment.setArguments(args);
		
		return fragment;
	}
}
